package jmu.db;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.sql.*;

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class ConnectionManager {
    private static String url;
    private static String username;
    private static String password;

    // 使用setter方法注入配置值到静态变量
    public void setUrl(String url) {
        ConnectionManager.url = url;
    }

    public void setUsername(String username) {
        ConnectionManager.username = username;
    }

    public void setPassword(String password) {
        ConnectionManager.password = password;
    }

    /** 返回连接 */
    public static Connection getConnection() {
        Connection dbConnection = null;
        try {
            String driverClassName = "com.mysql.cj.jdbc.Driver";
            Class.forName(driverClassName);
            dbConnection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dbConnection;
    }

    /** 关闭连接 */
    public static void closeConnection(Connection dbConnection) {
        try {
            if (dbConnection != null && (!dbConnection.isClosed())) {
                dbConnection.close();
            }
        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        }
    }

    /** 关闭结果集 */
    public static void closeResultSet(ResultSet res) {
        try {
            if (res != null) {
                res.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /** 关闭语句 */
    public static void closeStatement(PreparedStatement pStatement) {
        try {
            if (pStatement != null) {
                pStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeStatement(Statement statement) {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}